package com.xiaoxu.intranetweb.config;

import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FastJsonConfiguration {
    @Bean
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        // 创建FastJson消息转换器
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        // 创建FastJson配置对象
        FastJsonConfig config = new FastJsonConfig();
        // 设置全局日期格式
        config.setDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        // 配置全局序列化特性
        SerializerFeature[] features = new SerializerFeature[]{
                SerializerFeature.WriteMapNullValue, // 是否输出值为null的字段,默认为false
                SerializerFeature.WriteNullListAsEmpty, // 空集合输出[]而非null
                SerializerFeature.WriteNullStringAsEmpty // 字符串类型字段如果为null,输出为"",而非null
        };
        config.setSerializerFeatures(features);
        // 将配置对象设置到转换器中
        converter.setFastJsonConfig(config);
        return new HttpMessageConverters(converter);
    }
}